<template>
  <scroll-view scroll-y="ture" style="height: 100vh">
    <template v-if="activityStatus === '活动中'">
      <view
        class="panda-container"
        :style="{
          backgroundImage: `url(${oss2('others/minioreo-panda/index_bg.png')})`,
        }"
      >
        <view
          class="my"
          :style="{
            backgroundImage: `url(${oss2(
              'others/minioreo-panda/button_my.png'
            )})`,
          }"
          @click.stop="toMy"
        ></view>

        <view
          class="rule"
          @click.stop="openRule"
          :style="{
            backgroundImage: `url(${oss2(
              'others/minioreo-panda/button_explain.png'
            )})`,
          }"
        ></view>

        <view
          class="desire"
          @click.stop="toDesire"
          :style="{
            backgroundImage: `url(${oss2(
              'others/minioreo-panda/button_desire.png'
            )})`,
          }"
        ></view>

        <view
          class="wishGranter"
          @click.stop="toScanCode"
          :style="{
            backgroundImage: `url(${oss2(
              'others/minioreo-panda/button_xy.png'
            )})`,
          }"
        ></view>

        <view class="agree">
          <view class="flex items-center justify-center">
            <template>
              <image
                v-if="iAgree"
                class="i-agree"
                :src="ossImg('others/panda2023/choose.png')"
                @click.stop="doAgree"
              />
              <view v-else class="i-agree" @click.stop="doAgree"> </view>
            </template>
            <view class="agree-content">
              已阅读并同意
              <view class="link" @click.stop="openRule2">活动规则</view>
            </view>
          </view>
        </view>
      </view>
    </template>

    <template v-else>
      <view
        class="panda-container puzzle"
        :style="{
          backgroundImage: `url(${
            activityStatus === '未开始'
              ? oss2('others/minioreo-panda/NotStarted_pic.png')
              : activityStatus === '已结束'
              ? oss2('others/minioreo-panda/puzzle_js.png')
              : oss2('others/minioreo-panda/puzzle_fm.png')
          })`,
        }"
      >
        <view
          class="backHomeBtn"
          @click.stop="backHome"
          :style="{
            backgroundImage: `url(${oss2(
              'others/minioreo-panda/Button_back.png'
            )})`,
          }"
        ></view>
      </view>
    </template>

    <!-- 弹窗-许愿次数已达上限 -->
    <view class="mode" v-if="showDialog2">
      <view
        class="Dialog_body w-306px h-233px top-204px left-34.5px"
        :style="{
          backgroundImage: `url(${oss2('others/minioreo-panda/tk_bg2.png')})`,
        }"
        ><view
          class="Dialog_back w-119px h-44.5px bottom-57.5px left-93.5px"
          @click.stop="closeDialog2"
          :style="{
            backgroundImage: `url(${oss2(
              'others/minioreo-panda/button1.png'
            )})`,
          }"
        ></view>
        <view class="Dialog_rule"
          >查看<span class="link" @click.stop="openRule3">活动规则</span>
        </view>
      </view>
    </view>

    <!-- 活动规则弹窗 -->
    <rule-popup v-if="showRule" @close="closeRule" />
  </scroll-view>


</template>

  <script setup>
import {
  onLoad,
  onShow,
  onUnload,
  onHide,
  onShareAppMessage,
} from "@dcloudio/uni-app";
import { ref } from "vue";
import { ossImg, oss2, message } from "@/utils/utils";
import RulePopup from "./components/rule-popup.vue";
import { userLogin } from "@/services/utils";
import privacyPopup from "@/components/privacy-popup";

let enterTime = "";
let outTime = "";
let stayTime = "";
let emdlzMap = {
  活动中: "mini_oreo_campaign_wish_page",
  未开始: "mini_oreo_campaign_wish_ready_page",
  已结束: "mini_oreo_campaign_wish_end_page",
};

const activityStatus = ref("已结束");
const iAgree = ref(false);

const showDialog2 = ref(false);
const showRule = ref(false);
const LuckTimes = ref(0);
const version = ref("");

onLoad(async (options) => {});

onShow(() => {
  // 用户进入时间
  enterTime = new Date();

  getApp().accessLogAdd();
  if (uni.getStorageSync("MINIAGREE")) {
    iAgree.value = uni.getStorageSync("MINIAGREE");
  }
  if (activityStatus.value !== "未开始") {
    uni.login({
      provider: "weixin",
      success: async (res) => {
        const loginParam = {
          type: 1,
        };
        loginParam.code = res.code;

        const { data } = await userLogin(loginParam);
        uni.setStorageSync("OPENID", data?.openId);
        uni.setStorageSync("UNIONID", data?.unionId);
        uni.setStorageSync("TOKEN", data?.accessToken);
        getApp().emdlz2("set", "user", "openid", data.openId);
        getApp().emdlz2("set", "user", "unionId", data.unionId);
        getTimes(data?.unionId);
        getVersion();
        getApp().getUserInfo();
      },
    });
  }
});

onHide(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime?.getTime() - enterTime?.getTime()) / 1000;
  getApp().emdlz2(
    "track",
    "event",
    emdlzMap[activityStatus.value],
    "view",
    "campaign_landpage",
    stayTime
  );
  // if (activityStatus.value === "活动中") {
  //   getApp().emdlz2(
  //     "track",
  //     "event",
  //     "mini_oreo_campaign_wish_page",
  //     "view",
  //     "campaign_landpage",
  //     stayTime
  //   );
  // } else if (activityStatus.value === "未开始") {
  //   getApp().emdlz2(
  //     "track",
  //     "event",
  //     "mini_oreo_campaign_wish_ready_page",
  //     "view",
  //     "campaign_landpage",
  //     stayTime
  //   );
  // } else if (activityStatus.value === "已结束") {
  //   getApp().emdlz2(
  //     "track",
  //     "event",
  //     "mini_oreo_campaign_wish_end_page",
  //     "view",
  //     "campaign_landpage",
  //     stayTime
  //   );
  // }
});

onUnload(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime?.getTime() - enterTime?.getTime()) / 1000;
  getApp().emdlz2(
    "track",
    "event",
    emdlzMap[activityStatus.value],
    "view",
    "campaign_landpage",
    stayTime
  );
});

const backHome = () => {
  getApp().emdlz2(
    "track",
    "event",
    emdlzMap[activityStatus.value],
    "click",
    "return"
  );
  // if (activityStatus.value === "未开始") {
  //   getApp().emdlz2(
  //     "track",
  //     "event",
  //     "mini_oreo_campaign_wish_ready_page",
  //     "click",
  //     "return",
  //     ""
  //   );
  // } else if (activityStatus.value === "已结束") {
  //   getApp().emdlz2(
  //     "track",
  //     "event",
  //     "mini_oreo_campaign_wish_end_page",
  //     "click",
  //     "return",
  //     ""
  //   );
  // }
  uni.switchTab({
    url: "/pages/home/home",
  });
};

const doAgree = () => {
  getApp().emdlz2(
    "track",
    "event",
    "mini_oreo_campaign_wish_page",
    "click",
    "agree_button",
    ""
  );
  iAgree.value = !iAgree.value;
  uni.setStorageSync("MINIAGREE", iAgree.value);
};

const getTimes = (unionid) => {
  uni.request({
    url: `${process.env.MINI_PANDA_URL}/OreoPanda/getTodayWishTimesByUnionid`,
    method: "post",
    data: {
      unionid: unionid,
    },
    header: {
      "Content-Type": "application/x-www-form-urlencoded",
    },

    success(res) {
      if (res.data.errorcode === 0) {
        LuckTimes.value = res.data.data.times;
      } else {
        uni.showToast({
          title: res.data.errordesc,
          icon: "none",
        });
      }
    },
    fail(err) {
      uni.showToast({
        title: err,
        icon: "none",
      });
    },
  });
};

const getVersion = () => {
  uni.request({
    url: `${process.env.PANDA_URL}/OreoPanda/getVersion`,
    method: "get",
    header: {
      "Content-Type": "application/x-www-form-urlencoded",
    },

    success(res) {
      if (res.data.errorcode === 0) {
        version.value = res.data.data.version;
      } else {
        uni.showToast({
          title: res.data.errordesc,
          icon: "none",
        });
      }
    },
    fail(err) {
      uni.showToast({
        title: err,
        icon: "none",
      });
    },
  });
};

const toScanCode = () => {
  getApp().emdlz2(
    "track",
    "event",
    "mini_oreo_campaign_wish_page",
    "click",
    "start_wish_machine",
    ""
  );
  if (!iAgree.value) return message("请先同意相关协议!");
  if (LuckTimes.value === 0) return (showDialog2.value = true); // 次数已达上限
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const pageUrl = currentPage.$page.fullPath;
  linkTo(
    `/pages/webView/miniWebview?token=${uni.getStorageSync(
      "TOKEN"
    )}&openid=${uni.getStorageSync("OPENID")}&unionid=${uni.getStorageSync(
      "UNIONID"
    )}&memberid=${
      getApp().globalData.user.memberScore.memberId
    }&webSrc=${`${process.env.MINI_PANDA_URL}/#/pages/wish/wish`}&shareTitel=一口一个 好吃好玩&shareImg=${oss2(
      "others/minioreo-panda/share.png"
    )}&path=${
      pageUrl + `?from=pubid:shareback;aid:minicard`
    }&agree=${uni.getStorageSync("MINIAGREE")}&version=${version.value}`
  );
};

const toDesire = () => {
  getApp().emdlz2(
    "track",
    "event",
    "mini_oreo_campaign_wish_page",
    "click",
    "wish_wall",
    ""
  );

  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const pageUrl = currentPage.$page.fullPath;
  if (!iAgree.value) return message("请先同意相关协议!");
  linkTo(
    `/pages/webView/miniWebview?token=${uni.getStorageSync(
      "TOKEN"
    )}&openid=${uni.getStorageSync("OPENID")}&unionid=${uni.getStorageSync(
      "UNIONID"
    )}&memberid=${
      getApp().globalData.user.memberScore.memberId
    }&webSrc=${`${process.env.MINI_PANDA_URL}/#/pages/wall/wall`}&shareTitel=一口一个 好吃好玩&shareImg=${oss2(
      "others/minioreo-panda/share.png"
    )}&path=${
      pageUrl + `?from=pubid:shareback;aid:minicard`
    }&agree=${uni.getStorageSync("MINIAGREE")}&version=${version.value}`
  );
};

const toMy = () => {
  if (!iAgree.value) return message("请先同意相关协议!");
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const pageUrl = currentPage.$page.fullPath;
  getApp().emdlz2(
    "track",
    "event",
    "mini_oreo_campaign_wish_page",
    "click",
    "wish_record",
    ""
  );
  linkTo(
    `/pages/webView/miniWebview?token=${uni.getStorageSync(
      "TOKEN"
    )}&openid=${uni.getStorageSync("OPENID")}&unionid=${uni.getStorageSync(
      "UNIONID"
    )}&memberid=${
      getApp().globalData.user.memberScore.memberId
    }&webSrc=${`${process.env.MINI_PANDA_URL}/#/pages/list/list`}&shareTitel=一口一个 好吃好玩&shareImg=${oss2(
      "others/minioreo-panda/share.png"
    )}&path=${
      pageUrl + `?from=pubid:shareback;aid:minicard`
    }&agree=${uni.getStorageSync("MINIAGREE")}&version=${version.value}`
  );
};

const openRule = () => {
  getApp().emdlz2(
    "track",
    "event",
    "mini_oreo_campaign_wish_page",
    "click",
    "check_activity_rule_2",
    ""
  );
  showRule.value = true;
};

const openRule2 = () => {
  getApp().emdlz2(
    "track",
    "event",
    "mini_oreo_campaign_wish_page",
    "click",
    "check_activity_rule_1",
    ""
  );
  showRule.value = true;
};

const closeDialog2 = () => {
  getApp().emdlz2(
    "track",
    "event",
    "mini_oreo_campaign_wish_page",
    "click",
    "return",
    ""
  );
  showDialog2.value = false;
};

const openRule3 = () => {
  getApp().emdlz2(
    "track",
    "event",
    "mini_oreo_campaign_wish_page",
    "click",
    "check_activity_rule_3",
    ""
  );
  showRule.value = true;
};

const closeRule = () => {
  getApp().emdlz2(
    "track",
    "event",
    "mini_oreo_campaign_wish_rule_page",
    "click",
    "shut_down",
    ""
  );
  showRule.value = false;
};

const linkTo = (url) => uni.navigateTo({ url });

onShareAppMessage((e) => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const pageUrl = currentPage.$page.fullPath;

  const shareObj = {
    title: "一口一个 好吃好玩", // 默认是小程序的名称(可以写slogan等)
    path: pageUrl + `?from=pubid:shareback;aid:minicard`, // 默认是当前页面，必须是以‘/’开头的完整路径
    imageUrl: oss2("others/minioreo-panda/share.png"), //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
    success: (res) => {
      // 转发成功之后的回调
      if (res.errMsg == "shareAppMessage:ok") {
      }
    },
    fail: (err) => {
      // 转发失败之后的回调
      console.log("转发失败之后的回调", err);
      if (res.errMsg == "shareAppMessage:fail cancel") {
        // 用户取消转发
        console.log("用户取消转发");
      } else if (res.errMsg == "shareAppMessage:fail") {
        // 转发失败，其中 detail message 为详细失败信息
        console.log("转发失败，其中detail message 为详细失败信息");
      }
    },
    complete: () => {
      // 转发结束之后的回调（转发成不成功都会执行）
      console.log("转发结束之后的回调（转发成不成功都会执行）");
    },
  };
  return shareObj;
});
</script>

  <style>
page {
  background-color: #1335b4 !important;
}
</style>
  <style lang="less" scoped>
@import "@/static/css/theme.less";

.puzzle {
  height: 1448rpx !important;
}
.panda-container {
  width: 375px;
  background-color: #1335b3;
  height: 728px;
  background-repeat: no-repeat;
  background-position: top left;
  background-size: 375px 100%;
  position: relative;

  .rule {
    position: absolute;
    width: 97px;
    height: 32px;
    right: 0;
    top: 18.5px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 97px 100%;
  }
  .desire {
    position: absolute;
    width: 81px;
    height: 32px;
    right: 0;
    top: 52.5px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 81px 100%;
  }

  .my {
    position: absolute;
    width: 94px;
    height: 32px;
    left: 0;
    top: 18.5px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 94px 100%;
  }
  .wishGranter {
    position: absolute;
    width: 175px;
    height: 48.5px;
    left: 105px;
    bottom: 115px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 165px 100%;
    z-index: 10;
  }

  .agree {
    font-size: 10px;
    color: #ffffff;
    box-sizing: border-box;
    z-index: 10;
    position: absolute;
    bottom: 74px;
    width: 100%;
    left: 0;

    .agree-content {
      word-break: break-all;
    }

    .link {
      color: #6ed4ff;
      display: inline-block;
      text-decoration: underline;
    }

    .i-agree {
      width: 10px;
      height: 10px;
      margin-right: 4px;
      background-color: #ffffff;
      box-sizing: border-box;
    }
  }
  .backHomeBtn {
    position: absolute;
    width: 223px;
    height: 53px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 223px 100%;
    bottom: 168px;
    left: 155rpx;
  }
}

.mode {
  width: 100%;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 90;
  background-color: rgba(10, 28, 108, 0.8);
  .Dialog_body {
    position: absolute;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 100% 100%;
    .Dialog_back {
      position: absolute;
      background-repeat: no-repeat;
      background-position: top left;
      background-size: 100% 100%;
    }
    .Dialog_rule {
      width: 100%;
      text-align: center;
      font-size: 12.5px;
      position: absolute;
      bottom: 22px;
      color: #0f2989;
      .link {
        color: #30a8fb;
        text-decoration: underline;
        margin-left: 5px;
      }
    }
  }
}
</style>
